package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.domain.OrderDO;
import com.jinzhi.jzweb.domain.OrganizationNewsDO;
import com.jinzhi.jzweb.domain.OrganizationRolesDO;
import com.jinzhi.jzweb.service.CoursesService;
import com.jinzhi.jzweb.service.OrderService;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.jzweb.service.OrganizationRolesService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <pre>
 * 订单表
 * </pre>
 * <small> 2020-05-14 09:52:15 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/order")
public class OrderController extends BaseController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
	@Autowired
	private CoursesService coursesService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private OrganizationRolesService organizationRolesService;

    @GetMapping()
    @RequiresPermissions("jzweb:order:order")
    String Order(Model model) {

        OrganizationNewsDO orgNews = organizationNewsService.selectById(this.getUser().getOrgId());
        if(orgNews != null){
            OrganizationRolesDO orgRole = organizationRolesService.findOneByKv("role_type" , 0 , "org_id" , orgNews.getId());
            if (orgRole != null){
                UserDO user = userService.selectById(orgNews.getLeadingCadreId());
                if (user != null){
                    model.addAttribute("money" , user.getMoney());
                }else {
                    model.addAttribute("money" , 0.00);
                }
            }else {
                model.addAttribute("money" , 0.00);
            }
        }else{
            model.addAttribute("money" , 0.00);
        }

        return "jzweb/order/order";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:order:order")
    public Result<Page<OrderDO>> list(OrderDO orderDTO) {
        Wrapper<OrderDO> wrapper = new EntityWrapper<OrderDO>().orderBy("id", false);
        if (orderDTO.getState() != null) {
            wrapper.eq("state", orderDTO.getState());
        }
        if (orderDTO.getType() != null) {
            wrapper.eq("type", orderDTO.getType());
        }
        if (orderDTO.getName() != null) {
            wrapper.like("name", orderDTO.getName());
        }
        if (StringUtils.isNotBlank(orderDTO.getUserName())) {
            Wrapper<UserDO> userWrapper = new EntityWrapper<UserDO>().like("username", orderDTO.getUserName());
            List<UserDO> userDOS = userService.selectList(userWrapper);
            String str = "";
            for (UserDO userDO : userDOS) {
                str = str + userDO.getId() + ",";
            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("user_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("user_id", null);
            }
        }

        //todo 暂时只考实习就业单位、培训机构、超级管理员的查看权限；
        String roleName = getRoleNames();
        if(roleName.contains("实习就业单位") || roleName.contains("培训机构")){
            String sttr = "";
            if (roleName.contains("实习就业单位")) {
                sttr = sttr + this.getUser().getOrgId() + ",";
            }
            if (roleName.contains("培训机构")) {
                List<CoursesDO> coursesDOS = coursesService.findByKv("org_id", this.getUser().getOrgId());//其他角色，比如培训机构
                for (CoursesDO coursesDO : coursesDOS) {
                    sttr = sttr + coursesDO.getId() + ",";
                }
            }

            if (StringUtils.isNotBlank(sttr)) {
                wrapper.in("object_id", sttr.substring(0, sttr.length() - 1));
            } else {
                wrapper.eq("object_id", null);
            }
        }

        Page<OrderDO> page = orderService.selectPage(getPage(OrderDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            OrderDO obj = (OrderDO) page.getRecords().get(i);
            if (obj.getUserId() != null) {
                UserDO userDO = userService.selectById(obj.getUserId());
                if (userDO != null) {
                    obj.setUserName(userDO.getUsername());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:order:add")
    String add() {
        return "jzweb/order/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:order:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        OrderDO order = orderService.selectById(id);
        model.addAttribute("order", order);
        return "jzweb/order/edit";
    }

    @Log("添加订单表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:order:add")
    public Result<String> save(OrderDO order) {
        orderService.insert(order);
        return Result.ok();
    }

    @Log("修改订单表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:order:edit")
    public Result<String> update(OrderDO order) {
        boolean update = orderService.updateById(order);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除订单表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:order:remove")
    public Result<String> remove(Long id) {
        orderService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除订单表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:order:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        orderService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

}
